/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * 递归找为空的子节点（前序遍历）
 * @param {TreeNode} root
 * @param {number} val
 * @return {TreeNode}
 */
var insertIntoBST = function(root, val) {
    if(root === null) return new TreeNode(val)
    searchIntoLevel(root,val)
    return root
};

function searchIntoLevel(root,val){
    if(root === null) return true
    if(val > root.val){
        if(root.right === null){
            root.right = new TreeNode(val)
            return true
        }
    }
    if(val < root.val){
        if(root.left === null){
            root.left = new TreeNode(val)
            return true
        }
    }

    if(val > root.val){
        searchIntoLevel(root.right,val)
    }else{
        searchIntoLevel(root.left,val)
    }
    return
}





/**
 * 迭代遍历
 * @param {TreeNode} root
 * @param {number} val
 * @return {TreeNode}
 */
var insertIntoBST = function (root, val) {
    if (root === null) return new TreeNode(val)

    let temp = root
    while (temp !== null) {
        if (val < temp.val) {
            if (temp.left === null) {
                temp.left = new TreeNode(val)
                return root
            } else {
                temp = temp.left
            }
        } else {
            if (temp.right === null) {
                temp.right = new TreeNode(val)
                return root
            } else {
                temp = temp.right
            }
        }
    }
};